<template>
  <div class="permission-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="handleAdd">新增权限</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="权限名称">
          <el-input v-model="searchForm.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限编码">
          <el-input v-model="searchForm.code" placeholder="请输入权限编码" clearable />
        </el-form-item>
        <el-form-item label="权限类型">
          <el-select v-model="searchForm.type" placeholder="请选择权限类型" clearable>
            <el-option label="菜单权限" value="menu" />
            <el-option label="操作权限" value="operation" />
            <el-option label="数据权限" value="data" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 权限列表 -->
      <el-table :data="filteredPermissions" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="权限名称" />
        <el-table-column prop="code" label="权限编码" width="150" />
        <el-table-column prop="type" label="权限类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeType(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="parentName" label="上级权限" width="120" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              :type="row.status === 'active' ? 'danger' : 'success'" 
              size="small" 
              @click="handleToggleStatus(row)">
              {{ row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 添加/编辑权限对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增权限' : '编辑权限'"
      width="600px"
    >
      <el-form :model="permissionForm" :rules="rules" ref="permissionFormRef" label-width="120px">
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="permissionForm.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限编码" prop="code">
          <el-input v-model="permissionForm.code" placeholder="请输入权限编码" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="permissionForm.type" placeholder="请选择权限类型" style="width: 100%">
            <el-option label="菜单权限" value="menu" />
            <el-option label="操作权限" value="operation" />
            <el-option label="数据权限" value="data" />
          </el-select>
        </el-form-item>
        <el-form-item label="上级权限" prop="parentId">
          <el-select 
            v-model="permissionForm.parentId" 
            placeholder="请选择上级权限" 
            clearable
            style="width: 100%"
          >
            <el-option 
              v-for="item in parentPermissions" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input 
            v-model="permissionForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入权限描述" 
          />
        </el-form-item>
        <el-form-item label="排序号" prop="sort">
          <el-input-number 
            v-model="permissionForm.sort" 
            :min="1" 
            :max="999"
            placeholder="请输入排序号"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="permissionForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 角色权限配置对话框 -->
    <el-dialog
      v-model="rolePermissionDialogVisible"
      title="角色权限配置"
      width="800px"
    >
      <el-form :model="rolePermissionForm" label-width="100px">
        <el-form-item label="角色名称">
          <el-input v-model="rolePermissionForm.roleName" disabled />
        </el-form-item>
        <el-form-item label="权限选择">
          <el-transfer
            v-model="rolePermissionForm.permissionIds"
            :data="allPermissions"
            :titles="['可选权限', '已选权限']"
            :props="{
              key: 'id',
              label: 'name'
            }"
            filterable
            filter-placeholder="请输入权限名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rolePermissionDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitRolePermission">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// import API functions - 暂时注释掉，使用模拟数据
// import { 
//   getPermissionList, 
//   createPermission, 
//   updatePermission, 
//   deletePermission, 
//   updatePermissionStatus,
//   updateRolePermissions
// } from '../api/permission.js'

// 数据
const loading = ref(false)
const permissions = ref([])
const searchForm = reactive({
  name: '',
  code: '',
  type: '',
  status: ''
})

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 权限对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const permissionFormRef = ref()
const permissionForm = reactive({
  id: null,
  name: '',
  code: '',
  type: 'menu',
  parentId: null,
  description: '',
  sort: 1,
  status: 'active'
})

// 角色权限配置对话框
const rolePermissionDialogVisible = ref(false)
const rolePermissionForm = reactive({
  roleId: null,
  roleName: '',
  permissionIds: []
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { pattern: /^[a-zA-Z_][a-zA-Z0-9_]*$/, message: '权限编码只能包含字母、数字和下划线，且不能以数字开头', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 权限类型映射函数
const getTypeType = (type) => {
  const typeMap = {
    'menu': 'primary',
    'operation': 'success',
    'data': 'warning'
  }
  return typeMap[type] || 'info'
}

const getTypeLabel = (type) => {
  const labelMap = {
    'menu': '菜单权限',
    'operation': '操作权限',
    'data': '数据权限'
  }
  return labelMap[type] || type
}

// 上级权限选项
const parentPermissions = computed(() => {
  return permissions.value.filter(item => item.type === 'menu' && item.id !== permissionForm.id)
})

// 所有权限（用于角色权限配置）
const allPermissions = computed(() => {
  return permissions.value.filter(item => item.status === 'active')
})

// 模拟数据
const mockPermissions = [
  {
    id: 1,
    name: '用户管理',
    code: 'user_manage',
    type: 'menu',
    parentId: null,
    parentName: '-',
    description: '用户管理相关权限',
    sort: 1,
    status: 'active'
  },
  {
    id: 2,
    name: '商品管理',
    code: 'product_manage',
    type: 'menu',
    parentId: null,
    parentName: '-',
    description: '商品管理相关权限',
    sort: 2,
    status: 'active'
  },
  {
    id: 3,
    name: '订单管理',
    code: 'order_manage',
    type: 'menu',
    parentId: null,
    parentName: '-',
    description: '订单管理相关权限',
    sort: 3,
    status: 'active'
  },
  {
    id: 4,
    name: '添加用户',
    code: 'user_add',
    type: 'operation',
    parentId: 1,
    parentName: '用户管理',
    description: '添加新用户权限',
    sort: 1,
    status: 'active'
  },
  {
    id: 5,
    name: '编辑用户',
    code: 'user_edit',
    type: 'operation',
    parentId: 1,
    parentName: '用户管理',
    description: '编辑用户信息权限',
    sort: 2,
    status: 'inactive'
  }
]

// 计算属性：过滤后的权限列表
const filteredPermissions = computed(() => {
  let result = permissions.value

  // 搜索过滤
  if (searchForm.name) {
    result = result.filter(item => 
      item.name.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }
  if (searchForm.code) {
    result = result.filter(item => 
      item.code.toLowerCase().includes(searchForm.code.toLowerCase())
    )
  }
  if (searchForm.type) {
    result = result.filter(item => item.type === searchForm.type)
  }
  if (searchForm.status) {
    result = result.filter(item => item.status === searchForm.status)
  }

  // 分页
  total.value = result.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 方法
const getPermissionListData = async () => {
  // 直接使用模拟数据，不调用API
  loading.value = true
  setTimeout(() => {
    permissions.value = [...mockPermissions]
    total.value = mockPermissions.length
    loading.value = false
  }, 500) // 添加小延迟模拟加载效果
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.code = ''
  searchForm.type = ''
  searchForm.status = ''
  currentPage.value = 1
}

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(permissionForm, {
    id: null,
    name: '',
    code: '',
    type: 'menu',
    parentId: null,
    description: '',
    sort: 1,
    status: 'active'
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(permissionForm, row)
  dialogVisible.value = true
}

const handleToggleStatus = async (row) => {
  const action = row.status === 'active' ? '禁用' : '启用'
  try {
    await ElMessageBox.confirm(
      `确定要${action}权限"${row.name}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 本地模拟状态切换，不调用API
    const newStatus = row.status === 'active' ? 'inactive' : 'active'
    row.status = newStatus
    ElMessage.success(`${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新权限状态失败:', error)
      ElMessage.error('更新权限状态失败，请稍后重试')
    }
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限"${row.name}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 本地模拟删除，不调用API
    const index = permissions.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      permissions.value.splice(index, 1)
      total.value = permissions.value.length
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除权限失败:', error)
      ElMessage.error('删除权限失败，请稍后重试')
    }
  }
}

const handleSubmit = () => {
  permissionFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          // 本地模拟添加权限
          const newPermission = {
            ...permissionForm,
            id: Math.max(...permissions.value.map(p => p.id)) + 1,
            parentName: permissionForm.parentId ? permissions.value.find(p => p.id === permissionForm.parentId)?.name || '-' : '-'
          }
          permissions.value.push(newPermission)
          total.value = permissions.value.length
          ElMessage.success('添加成功')
        } else {
          // 本地模拟编辑权限
          const index = permissions.value.findIndex(p => p.id === permissionForm.id)
          if (index > -1) {
            permissions.value[index] = {
              ...permissionForm,
              parentName: permissionForm.parentId ? permissions.value.find(p => p.id === permissionForm.parentId)?.name || '-' : '-'
            }
            ElMessage.success('编辑成功')
          }
        }
        dialogVisible.value = false
      } catch (error) {
        console.error('提交权限表单失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加失败，请稍后重试' : '编辑失败，请稍后重试')
      }
    }
  })
}

// 配置角色权限
const handleRolePermission = () => {
  rolePermissionForm.roleId = 1
  rolePermissionForm.roleName = '商品管理员'
  rolePermissionForm.permissionIds = [1, 2, 4]
  rolePermissionDialogVisible.value = true
}

const handleSubmitRolePermission = async () => {
  // 本地模拟角色权限配置，不调用API
  ElMessage.success('角色权限配置成功')
  rolePermissionDialogVisible.value = false
}

// 生命周期
onMounted(() => {
  getPermissionListData()
})
</script>

<style scoped>
.permission-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>